package org.csc.sss.api.controller.base;

import org.apache.commons.lang3.StringUtils;
import org.csc.sss.core.model.SysUser;
import org.csc.sss.core.repository.*;
import org.csc.sss.core.repository.impl.PersonRepositoryImpl;
import org.csc.sss.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.context.SecurityContextHolder;

public class BaseController {

	@Autowired
	public SysUserRepository sysUserRepository;
	@Autowired
	public PersonRepository personRepository;
	@Autowired
	public SysRoleRepository sysRoleRepository;
	@Autowired
	public SysUserRoleRepository sysUserRoleRepository;
	@Autowired
	public SysRolePermissionRepository sysRolePermissionRepository;
	@Autowired
	public SysPermissionRepository sysPermissionRepository;



	@Autowired
	public PersonRepositoryImpl personRepositoryImpl;

	/**
	 * 获取当前登录的用户
	 * @return
	 */
	public SysUser getUser() {
		if (SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof SysUser) {
			return (SysUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		}
		return  null;
	}

	/**
	 * 初始化 分页、排序
	 * @param page 页数
	 * @param seiz 每页的大小
	 * @param sortField 排序字段
	 * @param direction true => desc | false => asc
	 * @return
	 */
	protected PageRequest pageRequest(Integer page, Integer seiz, String sortField, Boolean direction) {
		page = null == page || page < 1 ? 1 : page;
		seiz = null == seiz || seiz < 10 ? 10 : seiz;
		Sort sort = null;
		if (null != direction && StringUtils.isNotBlank(sortField)) {
			sort = new Sort(direction == true ? Sort.Direction.DESC : Sort.Direction.ASC, sortField);
		}
		PageRequest pageRequest = new PageRequest(page - 1, seiz, sort);

		return pageRequest;
	}

	protected <V> Result<V> ok(V v) {
		return new Result<V>(Result.ResultCode.OK.getCode(), Result.ResultCode.OK.getValue(), v);
	}

	protected <V> Result<V> error(V v) {
		return new Result<V>(Result.ResultCode.ERROR.getCode(), Result.ResultCode.ERROR.getValue(), v);
	}

	protected Result ok() {
		return new Result(Result.ResultCode.OK.getCode(), Result.ResultCode.OK.getValue(), null);
	}

	protected Result error() {
		return new Result(Result.ResultCode.ERROR.getCode(), Result.ResultCode.ERROR.getValue(), null);
	}

	protected Result ok(Result.ResultCode code) {
		return new Result(code.getCode(), code.getValue(), null);
	}

	protected Result error(Result.ResultCode code) {
		return new Result(code.getCode(), code.getValue(), null);
	}

	protected Result ok(Result.ResultCode code, String msg) {
		return new Result(code.getCode(), msg, null);
	}

	protected Result error(Result.ResultCode code, String msg) {
		return new Result(code.getCode(), msg, null);
	}




}
